<template>
  <div class='container container-report' ref="app">
    <div v-if="!propHideHeader">
      <!--标题-->
      <div v-if="chartModel && chartModel.config && chartModel.config.name" class="title"
           style="text-align: center;    font-size: 18px;font-weight: bold; padding-bottom: 5px;line-height: 22px;display: block">
        {{chartModel.config.name}}
      </div>
      <!--子标题-->
      <div v-if="chartModel && chartModel.config && chartModel.config.subtitle" class="subtitle"
           style="text-align: center;    font-size: 12px;height:30px">
        {{chartModel.config.subtitle}}
        <span style="padding-left: 11px" v-if="strings.isNotBlank(chartModel.config.remarks)">({{chartModel.config.remarks}})</span>
      </div>
    </div>
    <!-- 查询区域 -->
    <div>
      <customForm :withRangeYMD="cpWithRangeYMD" @enter="queryFormSubmit" class="query-form"  :data="formData" ref="queryForm"  v-if="!propHideQueryForm && cpUserQuery.length > 0">
        <template #content>
          <customFormItem
            v-for="item in cpUserQuery" :key="item.field"
            :label="utilFieldMap.show(item.field,item.label,'report',null)"
            :name="item.field"
            :parent="_self"
            :form="formData"
            v-bind="getFormItemAttr(item)"
          />
        </template>
      </customForm>

      <div v-if="!propHideQueryForm" style="padding-top: 3px;padding-bottom: 5px;">
        <customSpace>
          <template #content>
            <customButton @click="handleQueryClick"  title="查询" theme="primary">
              <!--静态图标-->
              <template #iconLeft>
                <customImage :src="icon.toolbar.search" :width="15" :height="15" class="button-image"/>
              </template>
            </customButton>
            <customButton @click="handleUserQueryReset"  title="重置" theme="default">
              <!--静态图标-->
              <template #iconLeft>
                <customImage :src="icon.toolbar.reset" :width="15" :height="15" class="button-image"/>
              </template>
            </customButton>
            <customButton @click="handleClear"  title="更新数据" theme="danger" v-if="chartModel.config.flagTmptableClear"/>
            <customButton @click="handleExport"  title="导出" theme="default">
              <!--静态图标-->
              <template #iconLeft>
                <customImage :src="icon.toolbar.export" :width="15" :height="15" class="button-image"/>
              </template>
            </customButton>
            <customButton @click="handlePrintCommon"  title="打印" theme="default" v-if="showPrintCommon">
              <!--静态图标-->
              <template #iconLeft>
                <customImage :src="icon.toolbar.print" :width="15" :height="15" class="button-image"/>
              </template>
            </customButton>

            <!-- 自定义按钮 -->
            <customButton
              v-for="button in cpGetBtns"
              :key="button.key"
              :theme="button.type"
              :title="button.text"
              @click="handleExtClick(button.key)"
            >
            </customButton>

            <customButton @click="toggleForm"  :title="maxHeightAuto ? '折叠查询' : '展开查询'" theme="default"  v-show="showToggleBtn">
              <!--静态图标-->
              <template #iconLeft>
                <customImage :src="icon.toolbar.toggle" :width="15" :height="15" class="button-image"/>
              </template>
            </customButton>
            <customButton @click="handleClose"  title="关闭" theme="default" v-if="propShowClose == true">
              <!--静态图标-->
              <template #iconLeft>
                <customImage :src="icon.toolbar.close" :width="15" :height="15" class="button-image"/>
              </template>
            </customButton>
          </template>
        </customSpace>
      </div>
    </div>

    <!-- 报表显示区域 -->
    <div v-show="cpShowChart">
      <el-card class="box-card" v-if="!propHideHeader">
        <div slot="header" class="clearfix">
          <span>{{chartModel.config.name}}</span>
          <!--<el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
        </div>
        <div :id="`${propId}`" style="width: 100%"/>
      </el-card>
      <div :id="`${propId}`" style="width: 100%" v-if="propHideHeader"/>
    </div>
    <div class="block"/>
    <div v-show="cpShowGrid">
      <el-card class="box-card" v-if="!propOnlyChart && !propHideHeader">
        <vxe-grid :data="chartModel.data"
                  stripe
                  border
                  keep-source
                  show-overflow
                  resizable
                  import-config
                  size="medium"
                  :max-height="cpMaxHeight"
                  height="auto"
                  :toolbar="toolbar"
                  :footer-method="footerMethod"
                  :show-footer="cpShowFooter"
                  :sort-config="sortConfig"
                  @sort-change="sortChange"
                  sortable
                  highlight-hover-row
                  highlight-hover-column
                  highlight-current-row
                  ref="grid1"
                  @header-cell-click="handleGridHeaderClick"
                  :column-config="{minWidth: 120}"
                  style="width: 100%"
                  :cell-class-name="cellClassName"
                  @cell-click="cellClickEvent"
                  class="mytable"
                  :keyboard-config="{isArrow: true}"
                  auto-resize
                  sync-resize
                  :span-method="mergeRowMethod"
        >
          <vxe-table-column v-if="!chartModel.config.flagDynamicColumn" type="seq" align="center"
                            width="50" fixed="left"/>
          <vxe-table-column :visible="chartModel.config.flagCheckbox"
                            type="checkbox"
                            :selectable="true"
                            width="50"
                            align="center"
                            fixed="left"
          />
          <vxe-table-column :sortable="!col.flagDynamicColumn && !col.flagSortDisabled"
                            v-for="(col,index) in cpGridFields.filter(o => o.flagShow )"
                            :key="col.id" :field="col.field" :title="utilFieldMap.show(col.field,col.label,'report',cpReportKey)" :minWidth="col.width"
                            :show-summary="col.flag_show" :align="col.align" show-overflow-tooltip
                            :fixed="index==0 ? 'left' : strings.defaultString(col.fixed, null)"
                            :params="col"
          >
            <template slot-scope="scope">
              <template v-if="col.flagClick">
                <el-link type="primary" :underline="false" @click="doAfterFun(scope.row,col.field)"
                         :title="strings.defaultString(col.clickTitle,'点击进行操作')">{{scope.row[col.field]}}
                </el-link>
              </template>
              <template v-else>
                <div  v-if="col.queryType == 'select' && strings.isNotBlank(col.dict)">
                  <span remark="1" v-html="utils.getDictLabel(scope.row[col.field], col.dict, '')"></span>
                </div>
                <div :style="getColumnClass(scope.row,col.field)" v-else>
                  <span remark="2" v-html="utilFieldMap.value(col.field,scope.row[col.field],'report',cpReportKey)"></span>
                </div>
              </template>
            </template>
          </vxe-table-column>
        </vxe-grid>

        <el-row  >
          <el-col :span="12" v-if="!this.chartModel.config.flagTopSum && !propHideHeader && cpUserQuery.length > 0 && this.chartModel.sumData && this.chartModel.sumData.length >0">
            <div class="sum-left">
              <!-- 合计区域-->
              <el-form class="form-sum" :inline="true" ref="formSum"
                       v-if="!this.chartModel.config.flagTopSum && !propHideHeader && cpUserQuery.length > 0 && this.chartModel.sumData && this.chartModel.sumData.length >0 ">
                <el-form-item label="合计">
                </el-form-item>
                <el-form-item v-for="sumColumn in this.chartModel.sumData" :key="sumColumn.field" :label="utilFieldMap.show(sumColumn.field,sumColumn.label,'report',null, '总')"
                >
                  {{utilFieldMap.value(sumColumn.field,strings.defaultIfBlank(sumColumn.sum,0),'report',null)}}
                </el-form-item>
              </el-form>
            </div>
          </el-col>

          <el-col :span="!this.chartModel.config.flagTopSum && !propHideHeader && cpUserQuery.length > 0 && this.chartModel.sumData && this.chartModel.sumData.length >0 ? 12 : 24">
            <vxe-pager
              border
              v-if="showPagination"
              size="medium"
              :current-page="tablePage.currentPage"
              :page-size="tablePage.pageSize"
              :page-sizes="[10, 15, 30, 50, 100]"
              :total="tablePage.totalResult"
              :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
              @page-change="handlePageChange">
            </vxe-pager>
          </el-col>
        </el-row>
      </el-card>
      <vxe-grid :data="chartModel.data" v-if="!propOnlyChart && propHideHeader"
                stripe
                border
                keep-source
                show-overflow
                :show-footer="cpShowFooter"
                export-config
                import-config
                resizable
                size="medium"
                :toolbar="toolbar"
                :max-height="cpMaxHeight"
                height="auto"
                :footer-method="footerMethod"
                sortable
                :sort-config="sortConfig"
                @sort-change="sortChange"
                ref="grid1"
                highlight-hover-row
                highlight-hover-column
                highlight-current-row
                :checkbox-config="{labelField: '', checkMethod: checkMethod}"
                :column-config="{minWidth: 120}"
                style="width: 100%"
                :cell-class-name="cellClassName"
                @cell-click="cellClickEvent"
                class="mytable"
                :keyboard-config="{isArrow: true}"
                auto-resize
                sync-resize
                :span-method="mergeRowMethod"
      >
        <vxe-table-column type="seq" v-if="!chartModel.config.flagDynamicColumn" align="center" width="50" fixed="left"/>

        <vxe-table-column  v-for="(col,index) in cpGridFields.filter(o => o.flagShow)"
                          :sortable="!col.flagDynamicColumn && !col.flagSortDisabled"
                          :key="col.id" :field="col.field" :title="utilFieldMap.show(col.field,col.label,'report',cpReportKey)" :width="col.width"
                          :show-summary="col.flag_show" :align="col.align" show-overflow-tooltip
                           :fixed="index==0 ? 'left' : strings.defaultString(col.fixed, null)"
                           :style="{fontWeight: col.field == 'sumRight' ? 'bold' : 'normal'}"
        >
          <template slot-scope="scope">
            <template v-if="col.flagClick">
              <el-link type="primary" :underline="false" @click="doAfterFun(scope.row,col.field)"
                       :title="strings.defaultString(col.clickTitle,'点击进行操作')">{{scope.row[col.field]}}
              </el-link>
            </template>
            <template v-else>
              <div  v-if="col.queryType == 'select' && strings.isNotBlank(col.dict)">
                <span remark="3" v-html="utils.getDictLabel(scope.row[col.field], col.dict, '')"></span>
              </div>
              <div :style="getColumnClass(scope.row,col.field)" v-else>
                <span remark="4" v-html="utilFieldMap.value(col.field,scope.row[col.field],'report',cpReportKey)"></span>
              </div>
            </template>
          </template>


        </vxe-table-column>
      </vxe-grid>
      <vxe-pager
      border
      v-if="!propOnlyChart && propHideHeader && showPagination"
      size="medium"
      :current-page="tablePage.currentPage"
      :page-size="tablePage.pageSize"
      :page-sizes="[10, 15, 30, 50, 100]"
      :total="tablePage.totalResult"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
      @page-change="handlePageChange">
    </vxe-pager>
    </div>
  </div>
</template>

<script>
/*eslint-disable*/
  import {addResizeListener, removeResizeListener} from 'element-ui/src/utils/resize-event'
  import defaultTheme from '@/assets/echarts/theme.js'
  import reportAfterFuns from '@/util/const/reportAfterFuns.js'
  import reportClassFuns from '@/util/const/reportClassFuns.js'
  import reportGetBtnFuns from '@/util/const/reportGetBtnFuns.js'
  import reportAfterBtnFuns from '@/util/const/reportAfterBtnFuns.js'

  // 引入基本模板
  let echarts = require('echarts/lib/echarts')

  require('echarts/theme/macarons.js')
  require('echarts/theme/dark.js')

  // walden
  require('echarts/lib/chart/line')
  require('echarts/lib/chart/bar')
  require('echarts/lib/chart/pie')

  // 引入提示框和title组件
  require('echarts/lib/component/tooltip')
  require('echarts/lib/component/title')

  require('echarts/lib/component/legend')
  require('echarts/lib/component/legendScroll')
  require('echarts/lib/component/toolbox')

import XEUtils from 'xe-utils'
import customImage from '@/components/custom/form/customImage.vue'

  export default {
    name: 'report',
    data() {
      return {
        name: 'report',
        chartModel: {
          config: {},
          chartFields: [],          // 图表配置字段
          gridFields: [],    // 表格配置字段
          data: []
        },
        chart: null,
        exportFooterSignArr: [], //导出底部签名栏
        exportFooterSumArr: [], //导出底部合计区域栏
        pager: {
          total: 0,
          size: Math.ceil((window.innerHeight - 500) / 40),
          count: 0,
          current: 1
        },
        tablePage: {
          currentPage: 1, // 当前页
          pageSize: 15, // 每页记录条数
          totalResult: 0 //总记录数
        },
        data: [],
        toolbar: (() => {
          if (this.propHideHeader) return null
          return {
            refresh: false,
            import: false,
            export: false,
            print: false,
            zoom: true,
            custom: true
          }
        })(),

        sortConfig: {
          remote: true,
          trigger: 'cell'
        },
        isQuery: false,
        showToggleBtn: false,
        showPrintCommon: true,
        showPagination: false, //显示分页
        orderField: null,
        orderType: null,
        gridMaxHeight: 0,
        gridNoPageMaxHeight: '1000%',
        selectRow: null,
        selectColumn: null,
        titleMaxLength: 'auto',
        maxHeightAuto: false,
        columnsMap: {},
        formData: {},
        queryWrapperParam: null,
        icon: {
          // 列表右侧按钮
          column: {
            //删除
            delete: require('@/assets/icon/dataview/column/delete.png'),
            //编辑
            edit: require('@/assets/icon/dataview/column/edit.png'),
            // 查看
            view: require('@/assets/icon/dataview/column/view.png'),
          },
          // 列表顶部工具栏按钮
          toolbar: {
            //导出
            export: require('@/assets/icon/dataview/toolbar/export.png'),

            //打印
            print: require('@/assets/icon/dataview/toolbar/print.png'),

            //查询
            search: require('@/assets/icon/dataview/toolbar/search.png'),

            //重置
            reset: require('@/assets/icon/dataview/toolbar/reset.png'),
            //展开查询
            toggle: require('@/assets/icon/dataview/toolbar/toggle.png'),

            //关闭
            close: require('@/assets/icon/dataview/toolbar/close.png'),
          },
        }
      }
    },
    mounted() {
      echarts.registerTheme('default', defaultTheme)

      if (!(this.propNoAutoFetchData && this.propNoAutoFetchData == true)) {
        setTimeout( () => {
          this.fetchData(true)
        }, 100)
      }
    },
    components: { customImage },
    computed: {
      cpChartType() {
        let {config} = this.chartModel
        return config ? config.type : null
      },
      cpShowChart() {
        return this.chartModel.config.flagShowChart
      },
      cpShowGrid() {
        return this.chartModel.config.flagShowGrid
      },
      cpReportKey() {
        let {params} = this.$route
        return params.reportKey || this.propReportKey
      },
      cpInitOptions() {
        let options = {}
        if (this.strings.isNotBlank(this.propHeight)) {
          options.height = this.propHeight
        }

        if (this.strings.isNotBlank(this.propWidth)) {
          options.width = this.propWidth
        } else {
          let offsetWidth = this.$refs.app.offsetWidth
          options.width = (offsetWidth == 0 ? '90%' : offsetWidth - 30)
        }
        return options
      },
      cpUserQuery() {
        let {gridFields = []} = this.chartModel
        if (!gridFields) {
          return  []
        }
        return gridFields.filter(o => this.strings.isNotBlank(o.queryType))
      },

      //获取扩展按钮
      cpGetBtns() {
        if (!this.chartModel.config.getBtnFun) return []
        return reportGetBtnFuns[this.chartModel.config.getBtnFun](this)
      },

      //是否显示底部合计
      cpShowFooter() {
        return this.chartModel.config.flagDynamicColumn == true
      },

      //是否带年月日区间选择
      cpWithRangeYMD() {
        if (!this.cpUserQuery || this.cpUserQuery.length == 0) {
          return false
        }
        return this.cpUserQuery.filter(item => 'dateArea' == item.queryType).length > 0
      },

      //表格列
      cpGridFields() {
        if (!this.chartModel || !this.chartModel.gridFields) {
          return []
        }
        return this.chartModel.gridFields
      },

      cpMaxHeight() {
        //!showPagination ? gridNoPageMaxHeight : (gridMaxHeight!=0 ? gridMaxHeight : propHeight
        if (!this.showPagination) {
          return this.gridNoPageMaxHeight
        }
        if (!this.gridMaxHeight != 0 ) {
          return this.gridMaxHeight
        }
        return this.propHeight
      }
    },
    props: {
      propReportKey: {
        type: String,
        /*required: true*/
      },
      propPageSize: {
        type: Number,
      },
      propId: {
        type: String,
        default: () => `${parseInt(Math.random() * 10000, 10)}`
      },
      propFontSize: {
        type: Number,
        default: () => {
          return 14
        }
      },
      propHeight: {
        type: [String, Number],
        default: () => window.innerHeight * 2 / 3
      },
      propWidth: {
        type: [String, Number]
      },
      propTheme: {
        type: [String],
        // 主题. 可取值: default、macarons、dark
        default: () => 'macarons'
      },
      propXAxisLabelLengthPerRow: {
        type: [Number],
        default: () => null
      },
      propOptions: {},
      propParams: {}, // 查询参数
      propQueryWrapper: null,
      /**
       * 获取Series Data的方法
       * @param  data  数据
       * @param  labelField 标签字段名
       * @param valueField 值字段名称
       * @returns Array
       *
       */
      getSeriesDataMethod: {
        type: Function,
        default: (data, labelField, valueField) => {
          return data.map(item => item[valueField])
        }
      },
      // true 隐藏标题
      propHideHeader: {
        type: Boolean
      },
      // true 隐藏查询表单
      propHideQueryForm: {
        type: Boolean
      },
      propOnlyChart: {
        type: Boolean
      },
      //是否显示关闭按钮，弹框打开时显示
      propShowClose: {
        type: Boolean
      },
      propOnlyFields: {
        type: Array,
        /*required: true*/
      },

      propNoAutoFetchData: {
        type: Boolean
      },
    },
    methods: {
      menuActiveCall() {
        this.handleQueryClick()
      },
      checkMethod({ row }){

        return true
      },
      getQueryWrapper() {
        let queryWrapper = this.$newWrapper()
        this.cpUserQuery.forEach(item => {
          //formData
          let field = item.field
          let queryType = item.queryType ? item.queryType : ''
          if (this.strings.isBlank(field)) {
            return true
          }
          let value = this.formData[field]
          if (this.strings.isBlank(value)) {
            return true
          }
          if (
            value.length != 2 && ['numberArea', 'dateArea'].includes(queryType)
          ) {
            return true
          }

          if (item.queryType === 'dateArea') {
            queryWrapper.between(field, value)
          } else if (item.queryType === 'select') {
            queryWrapper.eq(field, this.strings.trimrl(value))
          }  else {
            queryWrapper.like(field, this.strings.trimrl(value))
          }
        })
        //如果有排序，则至少需要一个查询条件，否则会报错
        if (this.orderField && (!queryWrapper._queryConditions || queryWrapper._queryConditions.length < 1)) {
          queryWrapper.eq('1', 1);
        }
        return queryWrapper
      },
      getQueryParams(){
        let queryConditions = []
        // 拼接初始条件
        if (this.propQueryWrapper) {
          queryConditions.push(...this.propQueryWrapper.queryConditions)
        }
        // 拼接初始条件
        if (this.queryWrapperParam) {
          queryConditions.push(...this.queryWrapperParam.queryConditions)
        }

        // 拼接用户查询条件
        let getQueryWrapper = this.getQueryWrapper()
        if (getQueryWrapper) {
          queryConditions.push(...getQueryWrapper.queryConditions)
        }
        if (queryConditions.length != 0) {
          return JSON.stringify(queryConditions)
        }
        return ''
      },
      getOrderParams(){
        let orderConditions = []
        // 拼接初始条件
        if (this.propQueryWrapper) {
          orderConditions.push(...this.propQueryWrapper.orderConditions)
        }
        // 拼接初始条件
        if (this.queryWrapperParam) {
          orderConditions.push(...this.queryWrapperParam.orderConditions)
        }

        // 拼接用户查询条件
        let getQueryWrapper = this.getQueryWrapper()
        if (getQueryWrapper) {
          orderConditions.push(...getQueryWrapper.orderConditions)
        }
        if (orderConditions.length != 0) {
          return JSON.stringify(orderConditions)
        }
        return ''
      },
      //queryWrapperParam 这个条件会固定显示
      fetchData(isInit = false, queryWrapperParam) {
        if (queryWrapperParam) {
          this.queryWrapperParam = queryWrapperParam
        }

        if (this.strings.isBlank(this.cpReportKey)) {
          return
        }
        let params = this.propParams || {}
        this.utilVue.loadShow(true)

        // 设置用户查询参数
        params.queryString = this.getQueryParams()
        params.orderString = this.getOrderParams()
        if (this.propPageSize) params.pageSize = this.propPageSize
        if (this.orderField && this.orderType) params.orderBy = ' ' + this.orderField + ' ' + this.orderType
        if (isInit == true) {
          // let paramsStatus = this.utils.loadUserState(this,'report_'+this.cpReportKey)
          // if (this.strings.isString(paramsStatus)) paramsStatus = JSON.parse(paramsStatus)
          // if (paramsStatus) {
          //   if (paramsStatus.currentPage) this.tablePage.currentPage = paramsStatus.currentPage
          //   if (paramsStatus.pageSize) this.tablePage.pageSize = paramsStatus.pageSize
          //   if (paramsStatus.maxHeightAuto) this.maxHeightAuto = paramsStatus.maxHeightAuto
          // }
        }else  {
          params.currentPage = this.tablePage.currentPage
          params.pageSize = this.tablePage.pageSize
          params.maxHeightAuto = this.maxHeightAuto
          // this.utils.updateUserState('report_'+this.cpReportKey, {
          //   currentPage: this.tablePage.currentPage,
          //   pageSize: this.tablePage.pageSize,
          //   maxHeightAuto: this.maxHeightAuto
          // }, this)
        }

        params.currPage = this.tablePage.currentPage
        params.pageSize = this.tablePage.pageSize
        if (this.propPageSize && this.propPageSize > 0) {
          params.pageSize = this.propPageSize
        }

        params.isInit = isInit
        let that = this
        let url = `/report/config/fetchData?reportKey=${this.cpReportKey}`
        this.$ajax.get(url, {
          params
        }).then(resp => {
          try {
            this.utilVue.loadHide()
            // 存储之前的查询的值
            let hisUserQuery = this.cpUserQuery
            this.chartModel = resp.data

            //字段map
            if (this.chartModel && this.chartModel.gridFields) {
              this.chartModel.gridFields.forEach(column => this.columnsMap[column.field] = column )
            }

            if (this.propOnlyFields && this.propOnlyFields.length > 0) {
              this.chartModel.gridFields = this.chartModel.gridFields.filter(column => this.propOnlyFields.includes(column.field) )
            }

            //动态列
            if (this.chartModel != null ) {
              if (this.chartModel.config.flagDynamicColumn || this.chartModel.config.flagFixedColumn) {
                let gridFieldsNew = this.chartModel.gridFields.filter(gridField => {
                  //二级分组显示或者指定了上级列
                  if (gridField.flagGroup == true || this.strings.isNotBlank(gridField.parentField)) return false
                  if (gridField.flagDynamicColumn || gridField.field == 'seq') {
                    gridField.sortable = false
                  } else {
                    gridField.sortable = true
                  }

                  let gridFieldsNew2 = this.chartModel.gridFields.filter(gridField2 => gridField2.groupField == gridField.field || gridField2.parentField == gridField.field)
                  gridField.children = gridFieldsNew2
                  return gridField.flagShow
                })

                setTimeout(() => {
                  this.$refs.grid1.loadColumn(gridFieldsNew)
                }, 300)
              }

              // refreshColumn
              let titleMaxLengthTmp = 0
              this.chartModel.gridFields.filter(gf => this.strings.isNotBlank(gf.queryType)).forEach(o => {
                if (this.strings.lengthByte(o.label) > titleMaxLengthTmp) titleMaxLengthTmp = this.strings.lengthByte(o.label)
                let result = hisUserQuery.find(t => t.field == o.field)
                if (result) {
                  this.$set(o, 'value', result.value)
                  this.$set(o, 'value1', result.value1)
                }
              })
              if (titleMaxLengthTmp > 0) this.titleMaxLength = titleMaxLengthTmp * 10 + 'px'

              this.chartModel.gridFields.filter(field => this.strings.isNotBlank(field.dict)).forEach(field => {
                let fieldKey = field.field
                this.chartModel.data.forEach(data => {
                  let dataList = this.utils.getDictDataList(field.dict)
                  if (dataList && dataList.length > 0) {
                    let dict = dataList.find(dict => dict.value == data[fieldKey])
                    if (dict) {
                      data[fieldKey] = dict.label
                    }
                  }
                })
              })

              if (this.chartModel.config.flagShowChart) {
                this.drawChart()
              } else {

                setTimeout(() => {
                  let widthSUb = 0
                  if (that.$refs.queryForm && that.$refs.queryForm.$el) {
                    widthSUb = $(this.$refs.queryForm.$el).height()
                  }
                  if (that.$refs.formSum && that.$refs.formSum.$el) {
                    widthSUb += $(that.$refs.formSum.$el).height()
                  }
                  that.gridMaxHeight = window.innerHeight - 300
                  that.gridNoPageMaxHeight = window.innerHeight - 300 - widthSUb + 'px'

                  if (that.chartModel.config && this.chartModel.config.subtitle && that.chartModel.config.subtitle.length > 4) {
                    that.gridMaxHeight = window.innerHeight - 350
                  }
                  console.log('gridMaxHeight', that.gridMaxHeight)
                  if (this.$refs.grid1) {
                    that.$refs.grid1.refreshScroll(true)
                  }
                }, 1000)

              }
              this.showPagination = this.chartModel.config.flagPaging
              this.data = this.chartModel.data
              this.tablePage.totalResult = this.chartModel.totalCount ? Number(this.chartModel.totalCount) : 0
              this.loadPager()
              this.utilVue.loadHide(true)
              this.isQuery = false
              this.isShowToggleBtn()

              //resp 初始化查询日期的显示
              let initDateQueryField = this.chartModel.initDateQueryField
              let initDateQueryStart = this.chartModel.initDateQueryStart
              let initDateQueryEnd = this.chartModel.initDateQueryEnd
              if (initDateQueryField && initDateQueryStart && initDateQueryEnd) {
                setTimeout(() => {
                  if (initDateQueryStart.indexOf(' ') == -1) {
                    initDateQueryStart+=' 00:00:00'
                  }
                  this.$set(this.formData, initDateQueryField, [initDateQueryStart, initDateQueryEnd])
                  if (isInit == true) {
                    let fileInit = this.cpUserQuery.filter(item => item.field == initDateQueryField)[0]
                    let fieldLabel = utilFieldMap.show(fileInit.field,fileInit.label,'report',null)
                    // this.utilMessage.warning(`已默认显示${fieldLabel} 从 ${initDateQueryStart} 到 ${initDateQueryEnd} 的相关数据`, 5000)
                  }
                }, 500)
              }
            }
          }catch (e) {
            console.log('fetchData.e',e)
          }
        }).catch(e => {
          this.isQuery = false
        })
      },

      //导出数据
      handleExport() {
        if (this.strings.isBlank(this.cpReportKey)) {
          return
        }
        let params = this.propParams || {}
        params.queryString = this.getQueryParams()

        let orderBy = null
        if (this.orderField && this.orderType) orderBy = ' ' + this.orderField + ' ' + this.orderType
        if (!this.exportFooterSignArr || this.exportFooterSignArr.length < 1 && this.chartModel.config.footSign) this.exportFooterSignArr = eval(this.chartModel.config.footSign)
        global.utils.export('report', this.cpReportKey, params.queryString, orderBy, this.exportFooterSignArr, this.exportFooterSumArr)
      },
      drawLineBar() {
        let title = this.chartModel.config.name
        let xAxis = this.chartModel.chartFields.filter(o => o.axis.toLowerCase() == 'X'.toLowerCase()).map(o => {
          return {
            type: 'category',
            data: this.chartModel.data.map(item => item[o.labelField]),
            axisLabel: {
              fontSize: this.propFontSize,
              formatter: this._axisLabelFormatter,
              rotate: 20   //调整数值改变倾斜的幅度（范围-90到90）
            },
            axisPointer: {
              type: 'shadow'
            }
          }
        })
        if (xAxis == null || xAxis.length == 0) {
          this.utilMessage.error('X轴坐标未设置值')
          return
        }

        let yAxis = this.chartModel.chartFields.filter(o => o.axis.toLowerCase() == 'Y'.toLowerCase()).map(o => {
          return {
            name: o.legend,
            type: 'value',
            axisLabel: {
              fontSize: this.propFontSize
            }
          }
        })

        if (yAxis == null || yAxis.length == 0) {
          yAxis = {
            type: 'value',
            axisLabel: {
              fontSize: this.propFontSize
            }
          }
        }

        let legend = {
          data: this.chartModel.chartFields.map(o => o.legend),
          bottom: 'left',
          y: 'top'
        }

        let series = this.chartModel.chartFields.filter(o => o.flagSeries).map(o => {
          let yAxisIndex = o.axis == 'Y' ? o.yAxisIndex : 0

          return {
            name: o.legend,
            type: o.seriesType,
            data: this.getSeriesDataMethod(this.chartModel.data, o.labelField, o.valueField),
            stack: this.strings.isBlank(o.stack) ? null : o.stack,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {propFontSize: this.propFontSize}
                }
              }
            },
            yAxisIndex,
            barWidth: 30,
            label: {
              normal: {
                show: true,
                textStyle: {
                  fontSize: this.propFontSize
                }
              },
              emphasis: {
                show: true
              }
            }
          }
        })

        let options = {
          // title: { text: title},
          textStyle: {
            fontSize: this.propFontSize
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '5%',
            containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            },
            textStyle: {
              fontSize: this.propFontSize
            },
          },
          toolbox: {
            show: true,
            feature: {
              magicType: {show: true, type: ['line', 'bar']},
              restore: {show: true},
              saveAsImage: {show: true}
            }
          },
          legend,
          xAxis,
          yAxis,
          series,
          dataZoom: [{
            type: 'slider',
            show: true, //flase直接隐藏图形
            xAxisIndex: [0],
            left: '9%', //滚动条靠左侧的百分比
            bottom: -5,
            start: 0,//滚动条的起始位置
            end: 100 //滚动条的截止位置（按比例分割你的柱状图x轴长度）
          }]
        }
        this.utils.mergeDeep(options, this.propOptions)
        // 绘制图表
        this.chart.setOption(options)
      },
      drawPie() {
        let len = this.chartModel.chartFields.filter(o => o.seriesType == 'pie').length
        if (len != 1) {
          // 如果有多个字段，另外处理
          return
        }
        let field = this.chartModel.chartFields.filter(o => o.seriesType == 'pie')[0]

        let title = this.chartModel.config.chartName
        let options = {
          title: {
            top: 20,
            textStyle: {
              color: '#ccc'
            }
          },
          grid: {
            left: '5%',
            right: '5%'
          },
          textStyle: {
            fontSize: this.propFontSize
          },
          tooltip: {
            textStyle: {
              fontSize: this.propFontSize
            },
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },

          /*legend: {
            bottom: 10,
            left: 'center',
            y: 'top',
            data: this.chartModel.data.map(item => {
              return item[field.labelField]
            })
          },*/
          series: [
            {
              name: field.legend,
              type: 'pie',
              radius: '55%',
              center: ['50%', '50%'],
              data: this.chartModel.data.map(item => {
                return {
                  value: item[field.valueField],
                  name: item[field.labelField]
                }
              }).sort((a, b) => {
                return a.value - b.value
              }),

              itemStyle: {
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
            }
          ]
        }
        this.utils.mergeDeep(options, this.propOptions)
        // 绘制图表
        this.chart.setOption(options)
      },
      handleGridHeaderClick(column, event) {
        let {roleCodes = [], code} = this.utils.getCurrentUser()
        let show = false
        if (code == 'admin' || roleCodes.includes('admin')) {
          show = true
        }
        if (!event.ctrlKey && !event.metaKey) {
          return
        }
        if (column.type == 'header' && show) {
          global.utils.openMenu('report/config/index',
            { id: this.chartModel.config.id })
        }
      },
      drawGauge() {
        // 仪表盘
        let series = this.chartModel.chartFields.filter(o => o.flagSeries).map(o => {
          return {
            name: o.legend,
            type: 'gauge',
            data: this.chartModel.data.map(item => {
              return {
                value: item[o.valueField]
              }
            })
          }
        })

        let options = {
          tooltip: {
            formatter: '{a} <br/>{b} : {c}%'
          },
          toolbox: {},
          series
        }

        this.utils.mergeDeep(options, this.propOptions)
        // 绘制图表
        this.chart.setOption(options)
      },
      drawChart() {
        // 基于准备好的dom，初始化echarts实例
        let dom = document.getElementById(this.propId)
        if (dom == null) {
          return
        }
        this.reset()
        // macarons dark
        if (!this.cpShowChart) {
          return
        }
        let theme = this.strings.defaultIfBlank(this.propTheme, 'macarons')
        this.chart = echarts.init(dom, theme, this.cpInitOptions)

        let chartType = this.cpChartType
        switch (chartType) {
          case 'line-bar':
            this.drawLineBar()
            break
          case 'pie':
            this.drawPie()
            break
          case 'gauge':
            this.drawGauge()
            break
          default:
            this.utilMessage.error('未实现的图表功能')
        }
        this.chart.resize()
        /*removeResizeListener(this.$refs.app, this.resizeListener)
        addResizeListener(this.$refs.app, this.resizeListener)*/
      },
      reset() {
        if (!this.chart) {
          return
        }
        this.chart.dispose()
        this.chart = null
      },
      resizeListener() {
        if (this.chart) {
          this.chart.resize()
        }
      },
      _axisLabelFormatter(value) {
        let maxLength = this.propXAxisLabelLengthPerRow //每项显示文字个数
        if (maxLength == null || maxLength <= 0) {
          return value
        }

        let ret = '' //拼接加\n返回的类目项

        let valLength = value.length //X轴类目项的文字个数
        let rowN = Math.ceil(valLength / maxLength) //类目项需要换行的行数
        if (rowN > 1) {
          // 如果类目项的文字大于1,
          for (let i = 0; i < rowN; i += 1) {
            let temp = ''//每次截取的字符串
            let start = i * maxLength//开始截取的位置
            let end = start + maxLength//结束截取的位置
            //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
            temp = value.substring(start, end) + '\n'
            ret += temp //凭借最终的字符串
          }
          return ret
        }
        return value
      },
      handleQueryClick() {
        this.isQuery = true
        this.tablePage.currentPage = 1
        this.fetchData()
      },
      handlePrintCommon() {
        let queryWrapper = this.getQueryWrapper()

        let head = []
        this.cpUserQuery.forEach(item => {
          let field = item.field
          let queryType = item.queryType ? item.queryType : ''
          if (this.strings.isBlank(field)) {
            return true
          }
          let value = this.formData[field]
          if (this.strings.isBlank(value)) {
            return true
          }
          if (
            this.strings.isBlank(value)
            && ['numberArea', 'dateArea'].includes(queryType)
          ) {
            return true
          }

          if (item.queryType === 'numberArea') {
            head.push({name: field, text: item.label, value: value.join(' 到 ')})
          } else if (item.queryType === 'dateArea') {
            head.push({name: field, text: item.label, value: value.join(' 到 ')})
          } else {
            head.push({name: field, text: item.label , value: value})
          }
        })

        let footSign = [
          {name: '1', text: '制表日期', col: 8},
          {name: '2', text: '制表人', col: 8},
          {name: '3', text: '复核人', col: 8},
        ]
        if (this.chartModel.config.footSign ) footSign = eval(this.chartModel.config.footSign)

        let param = {
          title: this.chartModel.config.name,
          subtitle: this.chartModel.config.subtitle,
          config: this.chartModel.config,
          queryWrapper: queryWrapper,
          form: {},
          head: head,
          foot: footSign
        }
        global.utilPrint.openReport([param])
      },
      handleUserQueryReset() {
        this.isQuery = true
        this.formData = {}
        if ($(".vxe-input--inner").length > 0) $(".vxe-input--inner").val('')
        this.orderField = null
        this.orderType = null
        this.fetchData()
      },
      //更新分页
      loadPager() {
        if (this.data == null || this.data.length < 1) {
          this.tablePage.totalResult = 0
          return
        }
      },
      //手动翻页
      handlePageChange(current) {
        this.tablePage.currentPage = current.currentPage
        this.tablePage.pageSize =  current.pageSize
        this.fetchData()
      },

      handleSizeChange(pageSizeNew) {
        this.tablePage.pageSize = pageSizeNew
        this.fetchData()
      },

      //获取下拉视图参数
      getPropUserParam(param) {
        return {viewKey: param.viewKey}
      },
      //获取下拉视图参数
      getPropUserParamMore(param) {
        let keepSelect =false
        if (param.queryField) keepSelect=true
        return {
          viewKey: param.viewKey,
          keepSelect: keepSelect,
          pkName: strings.camelCase(param.queryField)
        }
      },

      //选择完毕
      selectChange({fieldText,fieldId, columnProperty, row, rows, that}) {
        let rowValue
        let rowId
        if (row) {
          rowValue = row[columnProperty || fieldText]
          rowId = row[columnProperty || fieldId]
        } else if (rows){
          rowValue = []
          rowId = []
          rows.forEach(row1 => {
            rowValue.push(row1[columnProperty || fieldText])
            rowId.push(row1[columnProperty || fieldId])
          })
          this.$refs[fieldText][0].setSelectValue(rowValue.join(','))
        }
        this.chartModel.gridFields.forEach(o => {
          if (this.strings.camelCase(o.field) == fieldText) {
            let result = this.cpUserQuery.find(t => this.strings.camelCase(t.field) == fieldText)
            this.$set(o, 'value', rowValue)
            this.$set(o, 'value1', rowId)
            return false
          }
        })

        // this.handleQueryClick()
      },


      //执行后置方法
      doAfterFun(rowData, field) {
        let funName = this.chartModel.config.afterFun
        if (!funName) return {}
        reportAfterFuns[funName](rowData, field)
      },

      //获取列样式
      getColumnClass(rowData, fieldName) {
        let getClassFun = this.chartModel.config.getClassFun
        if (getClassFun) return reportClassFuns[getClassFun](rowData, fieldName)
        if (fieldName == 'sumRight') return {fontWeight: 'bold'}
        return {}
      },

      //扩展按钮点击
      handleExtClick(key) {
        reportAfterBtnFuns[this.chartModel.config.afterBtnFun](key, this.chartModel.config, this.data, this,this.$refs.grid1.getCheckboxRecords())
      },
      // 通用行合并函数（将相同多列数据合并为一行）
      mergeRowMethod ({ row, _rowIndex, column, columnIndex, visibleData }) {
        if (this.cpGridFields.length == 0) {
          return
        }
        let fields = this.cpGridFields.filter(o => o.flagShow)
        if (!this.chartModel.config.flagDynamicColumn) {
          if (columnIndex == 0) {
            return
          } else {
            columnIndex = columnIndex - 1
          }
        }
        let fieldFind = column.params
        if (!fieldFind || fieldFind.flagMergeCell) {
          return
        }
        const columnMerge = fieldFind.flagMergeCell
        const columnField = fieldFind.field
        // const prevCloumnField = columnIndex == 0 ? null : fields[columnIndex - 1]['field']
        const cellValue = row[columnField]
        if (cellValue && columnMerge) {
          const prevRow = visibleData[_rowIndex - 1]
          let nextRow = visibleData[_rowIndex + 1]
          // if (prevRow && prevRow[columnField] === cellValue && (columnIndex == 0 || (prevRow[prevCloumnField] == row[prevCloumnField]))) {
          if (prevRow && prevRow[columnField] === cellValue) {
            return { rowspan: 0, colspan: 0 }
          } else {
            let countRowspan = 1
            // while (nextRow && nextRow[columnField] === cellValue && (columnIndex == 0 || (nextRow[prevCloumnField] == row[prevCloumnField]))) {
            while (nextRow && nextRow[columnField] === cellValue ) {
             nextRow = visibleData[++countRowspan + _rowIndex]
            }
            if (countRowspan > 1) {
              return { rowspan: countRowspan, colspan: 1 }
            }
          }
        }
      },
      isShowToggleBtn() {
        setTimeout(() => {
          if (this.$refs.queryForm && this.$refs.queryForm.$el && $(this.$refs.queryForm.$el)[0].scrollHeight > 55) this.showToggleBtn = true
        }, 500)
      },

      toggleForm() {
        let form = $(this.$refs.queryForm.$el)
        if (form.hasClass('max-height-auto')) {
          form.removeClass('max-height-auto')
          this.maxHeightAuto = false
        } else {
          this.maxHeightAuto = true
          form.addClass('max-height-auto')
        }
      },

      //排序变化后
      sortChange({data, column, property, order}) {
        this.orderField = property
        if (!this.orderType) {
          this.orderType = order
        } else {
          if (this.orderType == 'asc') {
            this.orderType = 'desc'
          } else {
            this.orderType = 'asc'
          }
        }
        this.fetchData()
      },

      //获取全部数据
      async getAllData(reportCOde) {
        let retData = null
        let queryWrapper = this.getQueryWrapper()
        const params = {}
        if (queryWrapper && queryWrapper.queryConditions) params.queryString = JSON.stringify(queryWrapper.queryConditions)
        if (this.orderField && this.orderType) params.orderBy = ' ' + this.orderField + ' ' + this.orderType
        let url = `/report/config/fetchDataForPrint?reportKey=${reportCOde}`
        await this.$ajax.get(url, {params}).then((response) => {
          if (response.code == 0) {
            retData = response.data
          }
        })
        return retData
      },

      //合并表尾方法
      footerMethod({ columns, data }) {
        let sumROw = []
        if (this.chartModel.config.flagDynamicColumn != true&&this.chartModel.config.flagFixedColumn != true) return sumROw
        if (this.chartModel.config.flagBottomSum && this.chartModel.config.flagBottomSum == true) return sumROw
        sumROw = [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (columnIndex === 1) {
              return '总记录：' + this.chartModel.sumData[0].sum
            }
            let propertyold = column.property
            let property = column.property.toLowerCase()
            if (property.indexOf('amount') != -1 || property.indexOf('qty') != -1 || property.indexOf('sum') != -1 || property.indexOf('00') != -1 || this.columnsMap[propertyold].flagFootSum) {
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]

        this.exportFooterSumArr = sumROw[0]

        return sumROw
      },
      handleClose() {
        this.$emit('close')
      },
      //清空并刷新临时表
      async handleClear(){
        this.$confirm('是否清空并刷新该临时表？请不要在业务高峰期执行此操作，以免影响业务处理！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.utilVue.loadShow(true)
          this.$ajax.get(`/tool/reportTempTableClear/${this.chartModel.config.code}` ).then((response) => {
            if(response.code == 0 ){
              this.utilMessage.success(response.msg)
              this.handleQueryClick()
            }
            this.utilVue.loadHide()
          })
        }).catch(() => {
        });
      },
      cellClassName ({ row, column }) {
        if (row === this.selectRow & column === this.selectColumn) {
          return 'cell-select'
        }
      },
      cellClickEvent ({ row, column }) {
        this.selectRow = row
        this.selectColumn = column
      },

      // 获取表单项的其他属性
      getFormItemAttr(item) {
        let attr = {}
        let config = {}
        let queryType = item.queryType
        let type = this.constCommon.formItemType.inputText.name
        switch(queryType) {
          case "numberArea": {
            type = this.constCommon.formItemType.inputNumber.name
            break
          }
          case "dateArea": {
            type = this.constCommon.formItemType.datePickerRange.name
            break
          }
          case "dateyear": {
            type = this.constCommon.formItemType.datePicker.name
            config = this.constCommon.formItemType.datePicker.config.year
            break
          }
          case "datemonth": {
            type = this.constCommon.formItemType.datePicker.name
            config = this.constCommon.formItemType.datePicker.config.month
            break
          }
          case "select": {
            type = this.constCommon.formItemType.selectDict.name
            config.dictType = item.dict
            break
          }
          default: {

          }
        }
        attr.type = type
        attr.config = config
        return attr
      },
      // 表单提交
      queryFormSubmit(item) {
        this.handleQueryClick()
      }
    },
  }
</script>

<style lang="scss" >
  @import '../../styles/version1/report.scss';
</style>
